package com.winning.sx.microframework.dao.sysmanage;

import com.winning.dapi.data.api.IDataAccessService;
import com.winning.dapi.data.entity.DataTable;
//import com.winning.sx.microframework.model.exception.CustomException;
//import com.winning.sx.microframework.model.manage.ModelManageModel;
//import com.winning.sx.microframework.common.util.BaseUtil;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.manage.ModelManageModel;
import com.winning.sx.microframework.common.util.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by MJ on 2016-10-17.
 */
@Repository
public class ModelManageDao {
    @Autowired
    @Qualifier("dataSource")
    private IDataAccessService dataAccessService;

    public List<ModelManageModel> queryModels() throws CustomException {
        List<ModelManageModel> list = null;
        try {
            String sql = "select cModelID,cModelName,cFatherModelID,cURL,cInputTime,iOrder,icon from pm_models order by cFatherModelID,iOrder";
            list = dataAccessService.querySqlForBean(sql, ModelManageModel.class);
        } catch (Exception e) {
            throw new CustomException(-2001, "获取菜单失败");
        }
        return this.compositModels(list);
    }

    public List<ModelManageModel> queryModelsByID(Map<String, Object> map) throws CustomException {
        List<ModelManageModel> list = null;
        try {
            String sql = "select cModelID,cModelName,cFatherModelID,cURL,cInputTime,iOrder,icon from pm_models where cModelID =:cModelID order by cFatherModelID,iOrder";
            list = dataAccessService.querySqlUsingParamForBean(sql, ModelManageModel.class, map);
        } catch (Exception e) {
            throw new CustomException(-2001, "获取菜单失败");
        }
        return this.compositModels(list);
    }

    public List<ModelManageModel> queryModelsBySystemID(String systemid) throws CustomException {
        List<ModelManageModel> list = null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cSystemID", systemid);
        try {
            String sql = "SELECT  a.cModelID, " +
                    "        a.cModelName , " +
                    "        a.cFatherModelID , " +
                    "        a.cURL , " +
                    "        a.cInputTime , " +
                    "        a.iOrder ,a.icon " +
                    "FROM    pm_models a " +
                    "        LEFT JOIN PM_SystemASModel b ON a.cModelID = b.cModelID " +
                    "WHERE   b.cSystemID = :cSystemID " +
                    "UNION " +
                    "SELECT  DISTINCT(a.cModelID), " +
                    "        a.cModelName , " +
                    "        a.cFatherModelID , " +
                    "        a.cURL , " +
                    "        a.cInputTime , " +
                    "        a.iOrder ,a.icon " +
                    "FROM    pm_models a " +
                    "  LEFT JOIN pm_models c ON a.cModelID=c.cFatherModelID " +
                    "  LEFT JOIN PM_SystemASModel d ON c.cModelID=d.cModelID " +
                    "WHERE   d.cSystemID = :cSystemID " +
                    " order by cFatherModelID,iOrder";
            list = dataAccessService.querySqlUsingParamForBean(sql, ModelManageModel.class, map);
        } catch (Exception e) {
            throw new CustomException(-2001, "获取信息失败");
        }
        return this.compositModels(list);
    }

    public List<ModelManageModel> queryModelsByUserID(String usercode) throws CustomException {
        List<ModelManageModel> list = null;
        try {
            String sql = "select cModelID,cModelName,cFatherModelID,cURL,cInputTime,iOrder,icon from pm_models where cModelID in(select cModelID from pm_systemasmodel where cSystemID in (select cSystemID from pm_roleassystem where cRoleID in (select cRoleID from pm_userasrole where cUserCode =?))) order by cFatherModelID,iOrder";
            list = dataAccessService.querySqlForBean(sql, ModelManageModel.class, usercode);
        } catch (Exception e) {
            throw new CustomException(-2001, "获取信息失败");
        }
        return this.compositModels(list);
    }

    public static List<ModelManageModel> compositModels(List<ModelManageModel> webMenus) {
        //进行组装
        HashMap<String, ModelManageModel> webMenuHashMap = new HashMap<String, ModelManageModel>();
        List<ModelManageModel> topWebMenuList = new ArrayList<ModelManageModel>();

        for (ModelManageModel webMenu : webMenus) {
            webMenuHashMap.put(webMenu.getcModelID(), webMenu);

            if (StringUtils.isEmpty(webMenu.getcFatherModelID())) {
                topWebMenuList.add(webMenu);
                continue;
            }

            ModelManageModel parentMenu = webMenuHashMap.get(webMenu.getcFatherModelID());
            if (parentMenu == null)
                continue;

            if (parentMenu.getChildren() == null)
                parentMenu.setChildren(new ArrayList<ModelManageModel>());

            parentMenu.getChildren().add(webMenu);
        }

        return topWebMenuList;
    }

    public ModelManageModel newModel(ModelManageModel model) throws CustomException {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        model.setcInputTime(time);
        model.setcModelID(BaseUtil.createUUID());
        Map<String, Object> map = BaseUtil.beanToMap(model);
        try {
            String sql = "insert into pm_models(cModelID,cModelName,cFatherModelID,cURL,cInputTime,cDescribe,iOrder,icon) values(:cModelID,:cModelName,:cFatherModelID,:cURL,:cInputTime,:cDescribe,:iOrder,:icon)";
            dataAccessService.executeSqlUsingParam(sql, map);
        } catch (Exception e) {
            throw new CustomException(-2002, "新增模块失败");
        }
        return model;
    }

    public ModelManageModel updateModel(ModelManageModel model) throws CustomException {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        model.setcInputTime(time);
        Map<String, Object> map = BaseUtil.beanToMap(model);
        try {
            String sql = "update pm_models set icon=:icon,iOrder=:iOrder,cModelName=:cModelName,cFatherModelID=:cFatherModelID,cURL=:cURL,cInputTime=:cInputTime,cDescribe=:cDescribe where cModelID=:cModelID";
            dataAccessService.executeSqlUsingParam(sql, map);
        } catch (Exception e) {
            throw new CustomException(-2003, "更新模块失败");
        }
        return model;
    }

    public int deleteModel(String cModelID) throws CustomException {
        int result = -1;
        try {
            String sql = "SELECT cModelID FROM PM_Models WHERE cModelID=? OR cFatherModelID=?";
            DataTable dataTable = dataAccessService.querySql(sql, cModelID, cModelID);
            for (int i = 0; i < dataTable.getDataRows().size(); i++) {
                sql = "delete from PM_SystemAsModel where cModelID = ?";
                dataAccessService.executeSql(sql, dataTable.getDataRows().get(i).get("cModelID"));
            }
            sql = "delete from pm_models where cFatherModelID=?";
            result = dataAccessService.executeSql(sql, cModelID);
            sql = "delete from pm_models where cModelID=?";
            result += dataAccessService.executeSql(sql, cModelID);
        } catch (Exception e) {
            throw new CustomException(-2003, "删除模块失败");
        }
        return result;
    }

    public ModelManageModel loadModel(String cModelID) throws CustomException {
        ModelManageModel model = null;
        try {
            String sql = "select cModelID,cModelName,cFatherModelID,iOrder,cURL,cInputTime,cDescribe,icon from pm_models where cModelID=?";
            model = dataAccessService.querySqlForBean(sql, ModelManageModel.class, cModelID).get(0);
        } catch (Exception e) {
            throw new CustomException(-2001, "获取菜单失败");
        }
        return model;
    }
}
